package com.pz.account.service;

import com.pz.account.domain.model.MemberLoginParams;
import com.pz.account.domain.model.MemberLoginUser;
import com.pz.art.domain.AssoMember;
import com.pz.art.service.MemberService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.MobileLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.LoginParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.alibaba.druid.util.Utils.md5;

@Service
@Primary
public class AccountLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired(required = false)
    private MemberService memberService;

    @Autowired
    private MemberTokenService tokenService;

    private static final Logger log = LoggerFactory.getLogger(MobileLoginService.class);

    public AjaxResult registerUser(MemberLoginParams loginParams) {
        try{
            if (Objects.isNull(loginParams)) {
                return AjaxResult.error(-6,"参数为空");
            }
            String phoneNo = loginParams.getPhone();
            if (StringUtils.isBlank(phoneNo)) {
                return AjaxResult.error(-6,"发送手机号不能为空");
            }
            String validCode = loginParams.getValidCode();
            if (StringUtils.isBlank(validCode)) {
                return AjaxResult.error(-6,"验证码不能为空");
            }
            loginParams.setName(phoneNo);
            loginParams.setPassword(phoneNo);
            loginParams.setLoginType("1");
            return  this.login(loginParams);
        }catch (Exception e){
            throw new ServiceException(e.getMessage());
        }
    }

    private AjaxResult login(MemberLoginParams loginParams) {
        log.debug("login and loginParams:{}", loginParams);
        System.out.println(11);
        if (Objects.isNull(loginParams)) {
            return AjaxResult.error(-6, "登录参数不能为空");
        }
        String loginType = loginParams.getLoginType();
        if (StringUtils.isBlank(loginType)) {
            return AjaxResult.error(-6, "登录方式不能为空");
        }
        //登录方式0验证码登录，1用户名密码登录，2本机一键登录，3微信单点登录
        if (loginType.equals("0")) {
            String phoneNo = loginParams.getPhone();
            if (StringUtils.isBlank(phoneNo)) {
                return AjaxResult.error(-6, "登录名不能为空");
            }
            String validCode = loginParams.getValidCode();
            //2表示登录验证码，校验验证码合法性
            //sysSmsSendService.checkValidCode(phoneNo,validCode,"2");
            loginParams.setPhone(phoneNo);
            loginParams.setPassword("SSO_LOGIN");
        } else if (loginType.equals("1")) {
            String password = loginParams.getPassword();
            if (StringUtils.isBlank(password)) {
                return AjaxResult.error(-6, "密码不能为空");
            }
        }
        // 用户验证
        Authentication authentication = null;
        try {
            //进行用户验证，去查找会员表中是否存在该会员，如果不存在则进行注册
            String password = (md5(loginParams.getPassword()));
            MemberLoginUser loginUser = new MemberLoginUser();
            AssoMember member = memberService.selectMemberByPhoneNo(loginParams.getName());
            if (Objects.isNull(member)){
                String registerpassword = (md5(loginParams.getName()));
                AssoMember registermember = new AssoMember();
                registermember.setAccount(loginParams.getName());
                registermember.setLogin_ip(IpUtils.getIpAddr());
                registermember.setCreate_time(DateUtils.getNowDate());
                registermember.setUnit_boolean(2);
                registermember.setPassword(registerpassword);
                registermember.setNickname("用户"+loginParams.getName());
                registermember.setPhone(loginParams.getName());
                registermember.setLogin_time(DateUtils.getNowDate());
                registermember.setSex(3);
                registermember.setStatus(1);
                registermember.setName(loginParams.getName());
                registermember.setAssociation_member(2L);
                registermember.setDirect_invitation(2L);
                registermember.setCreate_team(2L);
                memberService.insertAssoMember(registermember);
                AjaxResult ajax = AjaxResult.success("");
                String token = IdUtils.fastUUID();
                loginUser.setId(Long.valueOf(registermember.getId()));
                ajax.put("token", token);
                ajax.put("expired", loginUser.getExpireTime());
                ajax.put("user", registermember);
                ajax.put("isAgent", String.valueOf(true));
                return ajax;
            }
            if (Objects.isNull(member.getUnit_id())){
                member.setMember_unit_name("普通会员");
            } else {
                member.setMember_unit_name(memberService.getAssomemberByUnitId(Long.valueOf(member.getUnit_id())).get(0).getMember_unit_name());
            }
            System.out.println("111222333");
            System.out.println(password);
            System.out.println(member.getPassword());
            //判断密码不等于输入密码即返回密码错误
            if (!member.getPassword().equals(password)){
                return AjaxResult.error("密码错误");
            }
            loginUser.setId(Long.valueOf(member.getId()));
            // 生成token
            String token = IdUtils.fastUUID();
//            String token = tokenService.createMemberToken(loginUser);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginParams.getName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            this.recordsMemeberLoginInfo(loginUser.getId());
            AjaxResult ajax = AjaxResult.success("");
            System.out.println("=====ts=====");
            System.out.println(token);
            System.out.println(loginUser.getUser());
            ajax.put("token", token);
            //token过期时间
            ajax.put("expired", loginUser.getExpireTime());
            ajax.put("user", member);
            ajax.put("isAgent", String.valueOf(true));
            return ajax;
        } catch (Exception e) {
            System.out.println(e);
            System.out.println(e.getStackTrace());
            return AjaxResult.error(-8, "密码错误");
        }
    }

    public void recordsMemeberLoginInfo(Long userId) {
        AssoMember assoMember = new AssoMember();
        assoMember.setId(Math.toIntExact(userId));
        assoMember.setLogin_ip(IpUtils.getIpAddr());
        assoMember.setLogin_time(DateUtils.getNowDate());
        assoMember.setUpdateTime(DateUtils.getNowDate());
        memberService.updateMember(assoMember);
    }
}
